<script setup>
import topNav from "../../components/topNav.vue";
import { introApi } from "@/services/index";
import { onLoad, onShow } from "@dcloudio/uni-app";
import { nextTick, ref, watch, onMounted } from "vue";
import { appInfo, loginSwitch } from "@/services/user";
// import topNav from "../../components/topNav.vue";
import { operation } from "@/utils/num.js";
import {
  appShopSelector,
  appScTransferCreate,
  appStoreCenterSelector,
} from "@/services/transfer";

import { PlanCreate, PlanUpdate } from "@/services/requiregoods";
const goodsList = ref([]);
const goodsList1 = ref([]);
const payNum = ref(0);
const payPrice = ref(0);
const oldPayPrice = ref(0);
const goodsListNo = ref([]);
const selectShopObj = ref({});
const topHeight = ref(uni.getStorageSync("topHight") || 0);
const description = ref("");

const expectDate = ref("");
const scId = ref("");
const products = ref([]);
const id = ref("");
onLoad((e) => {
  id.value = e.id ? e.id : "";
  getAppShopSelector();
  if (uni.getStorageSync("goodsSel")) {
    goodsList.value = JSON.parse(uni.getStorageSync("goodsSel"));
    goodsList.value.forEach((item, index) => {
      if (goodsList1.value.length == 0) {
        let arr = [];
        arr.push(item);

        goodsList1.value.push({
          supplierId: item.supplierId,
          supplierName: item.supplierName,
          miniPurchaseAmount: item.miniPurchaseAmount || 0,
          goodsList: [item],
          toPrice: operation(item.offerPrice, item.transferNum, 2, "multiply"),
          num: item.transferNum,
          diff: operation(
            Number(item.miniPurchaseAmount||0),
            operation(item.offerPrice, item.transferNum, 2, "multiply"),
            2,
            "subtract"
          ),
        });
      } else {
        let isHave = false;
        goodsList1.value.forEach((item1, index1) => {
          if (item1.supplierId == item.supplierId) {
            isHave = true;
            item1.goodsList.push(item);
            item1.toPrice = operation(
              item1.toPrice,
              operation(item.transferNum, item.offerPrice, 2, "multiply"),
              2,
              "add"
            );
            item1.num = operation(item1.num, item.transferNum, 2, "add");

            console.log(
              operation(item.offerPrice, item.transferNum, 2, "multiply")
            );
            item1.diff = operation(
              Number(item1.diff),
              operation(item.offerPrice, item.transferNum, 2, "multiply"),
              2,
              "subtract"
            );
          }
        });
        if (!isHave) {
          let arr = [];
          arr.push(item);
          goodsList1.value.push({
            supplierId: item.supplierId,
            supplierName: item.supplierName,
            miniPurchaseAmount: item.miniPurchaseAmount || 0,

            goodsList: [item],
            toPrice: operation(
              item.offerPrice,
              item.transferNum,
              2,
              "multiply"
            ),
            num: item.transferNum,
            diff: operation(
              Number(item.miniPurchaseAmount || 0),
              operation(item.offerPrice, item.transferNum, 2, "multiply"),
              2,
              "subtract"
            ),
          });
        }
      }

      payNum.value = payNum.value + item.transferNum;
      if (item.transferNum > 0) {
        payPrice.value = payPrice.value + 1;
      }
    });
    console.log(goodsList1.value);
  }

  if (uni.getStorageSync("shopselect")) {
    selectShopObj.value = JSON.parse(uni.getStorageSync("shopselect"));
  }
});

const ShopList = ref([]);
const showInShop = ref(false);
const selectid = ref("");
// showInShop.value = false;
// 门店选择
const shopSelectShow = () => {
  showInShop.value = true;
};

const getAppShopSelector = async () => {
  let res = await appStoreCenterSelector({});

  ShopList.value = res.data.datas;
  selectShopObj.value.targetShopId = ShopList.value[0].id;
  selectShopObj.value.targetShopName = ShopList.value[0].name;
};
const selectItem = ref({});
const shopSelect = (e) => {
  console.log(e);
  selectItem.value = e;
  selectid.value = e.id;
};
const selectTo = () => {
  selectShopObj.value.targetShopId = selectItem.value.id;
  selectShopObj.value.targetShopName = selectItem.value.name;
  uni.setStorageSync("shopselect", JSON.stringify(selectShopObj.value));

  showInShop.value = false;
};

const saveFun = () => {
  console.log("保存");
  //   console.log(form.value);
  // console.log(fileList.value[0].content);
  //   formMode.value.submit();
};
const value = ref(0);
const show = ref(false);

// 定义方法
const valChange = (e) => {
  console.log(e);

  let num = 0;
  let price = 0;

  setTimeout(() => {
    goodsList.value.forEach((item) => {
      num = num + item.transferNum;

      if (item.transferNum > 0) {
        price = price + 1;
      }
    });

    payPrice.value = price;
    payNum.value = num;
    uni.setStorageSync("goodsSel", JSON.stringify(goodsList.value));

    if (payNum.value == 0) {
      popupshow.value = false;
    }

    let toPrice = 0,
      num2 = 0,
      diff = 0;
    goodsList1.value.forEach((item) => {
      num2 = 0;
      toPrice = 0;
      diff = item.miniPurchaseAmount;

      item.goodsList.forEach((item1) => {
        console.log("1231232", item1);
        toPrice = operation(
          toPrice,
          operation(item1.transferNum, item1.offerPrice, 2, "multiply"),
          2,
          "add"
        );
        num2 = operation(num2, item1.transferNum, 2, "add");

        diff = operation(
          Number(diff),
          operation(item1.offerPrice, item1.transferNum, 2, "multiply"),
          2,
          "subtract"
        );
      });
      item.toPrice = toPrice;
      item.num = num2;
      item.diff = diff;
    });
  }, 100);
};
const confirmModal = () => {
  goodsList.value.forEach((item) => {
    item.transferNum = 0;
  });
  payNum.value = 0;
  show.value = false;
  uni.showToast({
    title: "清空成功",
    icon: "success",
    mask: true,
  });
  setTimeout(() => {
    if (id.value) {
      uni.redirectTo({
        url: "/pages/require_goods/goods_sel/index?id=" + id.value + "&clear=1",
      });
    } else {
      uni.redirectTo({ url: "/pages/require_goods/goods_sel/index" });
    }
  }, 1500);
};
const rightClick = () => {
  console.log("rightClick");
};

const leftClick = () => {
  console.log("leftClick");
};
// const goPay = () => {
//   uni.navigateTo({
//     url: "/pages/cashier/goods_confirm/index",
//   });
// };
//清空
const clearFun = () => {
  show.value = true;
};

//支付
const isPay = ref(false);

const goPay = async () => {
  if (!expectDate.value) {
    return uni.showToast({
      title: "请选择期望到货时间",
      icon: "none",
    });
  }

  if (isPay.value == true) {
    return;
  }

  isPay.value = true;
  uni.showLoading({
    title: "提交中",
    mask: true,
  });

  let data = [];
  let upPrice = 0;
  goodsList.value.forEach((element) => {
    console.log(element);
    // price: element.price,
    if (element.transferNum > 0) {
      data.push({
        productId: element.id,
        orderNum: element.transferNum,
        taxPrice: element.offerPrice ? element.offerPrice : 0,
        supplierId: element.supplierId,
      });
    }
  });

  if (data.length <= 0) {
    isPay.value = false;
    return uni.showToast({
      title: "请选择商品",
      icon: "none",
    });
  }

  uni.setStorageSync("goodsSel", JSON.stringify(goodsList.value));

  try {
    let res = null;
    if (id.value) {
      res = await PlanUpdate({
        id: id.value,
        scId: selectShopObj.value.targetShopId,
        expectDate: expectDate.value,
        products: data,
        description: description.value,
      });
      if (res.code == 200) {
        isPay.value = false;
        uni.hideLoading();
        uni.redirectTo({
          url:
            "/pages/require_goods/paystate/index?id=" +
            res.data.id +
            "&price=" +
            payPrice.value +
            "&payNum=" +
            payNum.value +
            "&upPrice=" +
            upPrice +
            "&uPid=" +
            id.value,
        });

        // let resData = res.data.datas;
      } else {
        uni.showToast({
          title: res.msg,
          icon: "none",
          mask: true,
        });
        isPay.value = false;
        uni.hideLoading();
      }
    } else {
      res = await PlanCreate({
        scId: selectShopObj.value.targetShopId,
        expectDate: expectDate.value,
        products: data,
        description: description.value,
      });
      if (res.code == 200) {
        isPay.value = false;
        uni.hideLoading();
        uni.redirectTo({
          url:
            "/pages/require_goods/paystate/index?id=" +
            res.data.id +
            "&price=" +
            payPrice.value +
            "&payNum=" +
            payNum.value +
            "&upPrice=" +
            upPrice,
        });

        // let resData = res.data.datas;
      } else {
        uni.showToast({
          title: res.msg,
          icon: "none",
          mask: true,
        });
        isPay.value = false;
        uni.hideLoading();
      }
    }
  } catch (e) {
    uni.showToast({
      title: e.msg,
      icon: "none",
      mask: true,
    });
    uni.hideLoading();
    isPay.value = false;
  }
};

const keyWord = ref(null);
const priceValue = ref(0);
const selectType = ref(1);
const selectTypeIndex = ref(0);
const selectItemObj = ref({});
const inp = (e) => {};

const hide = () => {
  // if (num.value > 0) {
  // } else {
  //   jsnum.value = 0;
  // }
  // isPayShow.value = false;
  keyWord.value.close();
};
const confirm = async () => {
  if (priceValue.value <= 0) {
    uni.showToast({
      title: "请输入正确金额",
      icon: "none",
    });
    return;
  }

  if (selectType.value == 1) {
    if (
      goodsList.value[selectTypeIndex.value].taxPrice < Number(priceValue.value)
    ) {
      uni.showToast({
        title: "商品调价不能大于售价",
        icon: "none",
      });
      keyWord.value.open();
      return;
    }

    goodsList.value[selectTypeIndex.value].taxPrice = Number(priceValue.value);
  }
  if (selectType.value == 2) {
    goodsListNo.value[selectTypeIndex.value].salePrice = Number(
      priceValue.value
    );
  }
  let num = 0;
  let price = 0;

  goodsList.value.forEach((item) => {
    num = num + item.transferNum;
    // price = operation(
    //   price,
    //   operation(item.transferNum, item.taxPrice, 2, "multiply"),
    //   2,
    //   "add"
    // );
  });

  payPrice.value = price;
  payNum.value = num;

  // getcomputeBrokerage(Number(num.value));
  // productDataNo.value[selectNo.value].salePrice = Number(priceValue.value);
  // productDataNo.value[selectNo.value].transferNum = 1;

  // payPrice.value = operation(
  //   payPrice.value,
  //   Number(priceValue.value),
  //   2,
  //   "add"
  // );
};
const closePay = () => {
  // isPayShow.value = false;
  keyWord.value.close();
};
const priceClick = (item, index, type) => {
  selectItemObj.value = item;
  selectTypeIndex.value = index;
  selectType.value = type;

  console.log("item", selectTypeIndex.value, selectType.value);
  if (type == 1) {
    priceValue.value = String(item.taxPrice);
    item.oldprice = item.price;
  }
  if (type == 2) {
    priceValue.value = String(item.salePrice);
  }
  keyWord.value.open();
};
//日期选择器
const showDate = ref(false);
const value1 = ref(Date.now() + 24 * 60 * 60 * 1000 * 1);
const minDate = ref(Date.now());

const confirmDate = (e) => {
  console.log(e.value, Time(e.value));
  expectDate.value = Time(e.value);
  showDate.value = false;
};

function Time(e) {
  const date = new Date(e);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0"); // 月份从0开始，需要加1
  const day = String(date.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
}
const selectDate = () => {
  showDate.value = true;
};
const goSearch = (id) => {
  uni.navigateTo({
    url: "/pages/require_goods/goods_search/index?supplierId=" + id,
  });
};
</script>

<template>
  <view class="bg">
    <topNav
      :title="'确认要货'"
      @save="saveFun"
      :border="true"
      rType="save"
    ></topNav>
    <!-- <up-navbar
      title="手机收银"
      bgColor="#ffffff"
      @rightClick="rightClick"
      :autoBack="true"
      :safeAreaInsetTop="true"
      :fixed="true"
      :placeholder="true"
      :leftText="'返回'"
      :border="true"
    >
      <template #right><text @click="clearFun">清空</text> </template>
    </up-navbar> -->
    <view class="content">
      <view
        class="content-top"
        :style="'top: calc( 88rpx + ' + topHeight + 'px);'"
      >
        <view class="content-top-shop" @click="selectDate">
          <view>
            <text>期望到货日期</text>
            <view class="content-top-des">需提前1天提交</view>
          </view>
          <view class="content-top-shop-right">
            <view class="content-top-shop-right-icon">
              <text :class="expectDate ? 'new_select' : ''"
                >{{ expectDate ? expectDate : "请选择" }}
              </text>
              <up-icon
                name="arrow-right"
                color="#86909C"
                size="30rpx"
              ></up-icon>
            </view>
            <!-- <up-icon name="arrow-right" color="#1679FB" size="30rpx"></up-icon> -->
          </view>
        </view>

        <view class="content-top-shop" @click="shopSelectShow">
          <view>
            <text>配送仓库</text>
            <!-- <view class="content-top-des">需提前2天提交</view> -->
          </view>
          <view class="content-top-shop-right">
            <view class="content-top-shop-right-icon">
              <text :class="selectShopObj.targetShopName ? 'new_select' : ''"
                >{{
                  selectShopObj.targetShopName
                    ? selectShopObj.targetShopName
                    : "请选择"
                }}
              </text>
              <up-icon
                name="arrow-right"
                color="#86909C"
                size="30rpx"
              ></up-icon>
            </view>
            <!-- <up-icon name="arrow-right" color="#1679FB" size="30rpx"></up-icon> -->
          </view>
        </view>
        <view class="content-top-up">
          <text>商品明细</text>
          <view class="content-top-shop-right" @click="clearFun"
            ><up-icon name="trash" color="#86909C" size="40rpx"></up-icon
            ><text>清空</text>
          </view>
        </view>
      </view>
      <view
        class="content-to"
        v-for="(item1, index1) in goodsList1"
        :key="index"
      >
        <view class="title-g">
          <view class="l">
            <view class="left" @click="goSearch(item1.supplierId)">
              {{ item1.supplierName }}
              <up-icon name="arrow-right" color="#86909C" size="30rpx"></up-icon
            ></view>
            <view class="right">满{{ item1.miniPurchaseAmount }}起送</view>
          </view>
        </view>
        <view
          class="content-item"
          v-for="(item, index) in item1.goodsList"
          :key="index"
          :class="index == item1.goodsList.length - 1 ? 'content-item2' : ''"
        >
          <view class="content-item-left"
            ><image :src="item.image" mode="scaleToFill"
          /></view>
          <view class="content-item-right">
            <view class="content-item-right-title">
              <text>{{ item.name }}</text>
            </view>
            <view class="content-item-right-index">
              <view>
                <view class="content-item-right-num">
                  <view class="content-item-right-num-left"
                    ><text>{{ item.categoryName }}</text>
                  </view>
                </view>
                <!-- @click="priceClick(item, index, 1)" -->
                <view class="content-item-right-price" v-if="item.offerPrice"
                  ><text>¥</text> {{ item.offerPrice }}
                  <text>{{ item.unit ? "/" + item.unit : "" }}</text></view
                >
                <view class="content-item-right-price" v-else
                  ><text>暂无报价</text>
                  <text>{{ item.unit ? "/" + item.unit : "" }}</text>
                </view>
              </view>
              <view class="content-item-right-num-right">
                <up-number-box
                  v-model="item.transferNum"
                  @change="valChange"
                  min="0"
                ></up-number-box>
              </view>
            </view>
          </view>
        </view>

        <view class="bt" v-if="item1.diff > 0">
          <view class="bt-k" @click="goSearch(item1.supplierId)">
            <view class="left"
              >不足起订量，再采购<text class="red">{{ item1.diff }}</text
              >元起送</view
            >
            <view class="right"
              ><text>去加购</text
              ><up-icon
                name="arrow-right"
                color="#ff5722"
                size="26rpx"
              ></up-icon
            ></view>
          </view>
        </view>
        <view class="num">
          <view class="num-k">
            共{{ item1.num }}件， 合计：<text>{{ item1.toPrice }}</text>
          </view>
        </view>
      </view>

      <view class="bz">
        <up-form labelPosition="left" ref="form1">
          <up-form-item label="备注" :borderBottom="false" ref="item1">
            <up-input
              v-model="description"
              border="none"
              inputAlign="right"
              placeholder="请输入备注信息"
            ></up-input>
            <template #right>
              <up-icon name="arrow-right"></up-icon>
            </template>
          </up-form-item>
        </up-form>
      </view>
    </view>
  </view>

  <view style="height: 150rpx; width: 100%"></view>

  <view class="bt_form">
    <view class="bt_form_k">
      <view class="bt_form_k_left">
        <view class="price">
          <view class="price-num"
            >共 <text class="blue">{{ payPrice }}</text
            >款, <text class="blue">{{ payNum }}</text
            >件</view
          ></view
        >
      </view>
      <view class="bt_pay" @click="goPay">提交申请</view>
    </view>
  </view>

  <up-modal
    :show="show"
    title="温馨提示"
    :showCancelButton="true"
    confirmText="确认"
    cancelText="取消"
    @cancel="show = false"
    @confirm="confirmModal"
  >
    <view class="slot-content">
      <rich-text :nodes="'确定清空选择商品？'"></rich-text>
    </view>
  </up-modal>

  <up-popup
    v-model:show="showInShop"
    round="10"
    @close="showInShop = false"
    :safeAreaInsetBottom="true"
    :closeable="true"
  >
    <view class="popup-content">
      <view class="popup-content-title">
        <text>{{ "门店" }}</text>
      </view>
      <view class="popup-content-list">
        <scroll-view
          scroll-y="true"
          class="scroll-Y"
          @scrolltoupper="upper"
          @scrolltolower="lower"
          @scroll="scroll"
        >
          <view
            class="scroll-to"
            v-for="(item, index) in ShopList"
            :key="index"
            @click="shopSelect(item, 1)"
          >
            <view
              class="scroll-to-title"
              :class="item.id == selectid ? 'scroll-to-title-sel' : ''"
            >
              <text>{{ item.name }}</text>
            </view>
            <up-icon
              v-if="item.id == selectid"
              name="checkbox-mark"
              color="#1679FB"
              size="40rpx"
            ></up-icon>
          </view>
        </scroll-view>
      </view>
      <view class="popup-content-btn">
        <up-button
          class="bt-qx"
          type="default"
          :plain="true"
          text="取消"
          @click="showInShop = false"
        ></up-button>
        <up-button type="primary" @click="selectTo()" text="确定"></up-button>
      </view>
    </view>
  </up-popup>

  <up-datetime-picker
    @cancel="showDate = false"
    :show="showDate"
    v-model="value1"
    mode="date"
    @confirm="confirmDate"
    :minDate="minDate + 60 * 60 * 1000 * 24 * 1"
  ></up-datetime-picker>
</template>

<style lang="scss" scoped>
@import "index.scss";
</style>
